<template>
  <div class="page-container">
    <h1 class="page-title">个人信息</h1>
    
    <el-row :gutter="20">
      <!-- 个人信息表单 -->
      <el-col :span="16">
        <div class="health-card">
          <div class="card-header">
            <h3>基本信息</h3>
          </div>
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="100px"
            class="profile-form"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="profileForm.username"
                disabled
                placeholder="用户名"
              />
            </el-form-item>
            
            <el-form-item label="真实姓名" prop="realName">
              <el-input
                v-model="profileForm.realName"
                placeholder="请输入真实姓名"
              />
            </el-form-item>
            
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="profileForm.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="profileForm.birthDate"
                type="date"
                placeholder="选择出生日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="disableFutureDate"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="profileForm.phone"
                placeholder="请输入手机号"
              />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="profileForm.email"
                placeholder="请输入邮箱"
              />
            </el-form-item>
            
            <el-form-item label="身高(cm)" prop="height">
              <el-input-number
                v-model="profileForm.height"
                :min="50"
                :max="250"
                :step="1"
                placeholder="请输入身高"
                style="width: 100%"
              />
            </el-form-item>
    
            
            <el-form-item label="健康目标" prop="healthGoal">
              <el-select
                v-model="profileForm.healthGoal"
                placeholder="请选择健康目标"
                style="width: 100%"
              >
                <el-option label="减重" value="减重" />
                <el-option label="增重" value="增重" />
                <el-option label="保持体重" value="保持体重" />
                <el-option label="增强体质" value="增强体质" />
                <el-option label="改善睡眠" value="改善睡眠" />
                <el-option label="缓解压力" value="缓解压力" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="健康备注">
              <el-input
                v-model="profileForm.healthNotes"
                type="textarea"
                :rows="3"
                placeholder="请输入健康备注信息，如过敏史、疾病史等"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updateProfile" :loading="updating">
                保存信息
              </el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      
      <!-- 修改密码 -->
      <el-col :span="8">
        <div class="health-card">
          <div class="card-header">
            <h3>修改密码</h3>
          </div>
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
            class="password-form"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入原密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请确认新密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updatePassword" :loading="passwordUpdating">
                修改密码
              </el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 健康数据统计 -->
        <div class="health-card" style="margin-top: 20px;">
          <div class="card-header">
            <h3>健康数据统计</h3>
          </div>
          <div class="stats-container">
            <div class="stat-item">
              <div class="stat-label">记录天数</div>
              <div class="stat-value">{{ healthStats.recordDays }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">运动次数</div>
              <div class="stat-value">{{ healthStats.exerciseCount }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">饮食记录</div>
              <div class="stat-value">{{ healthStats.dietCount }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">AI建议次数</div>
              <div class="stat-value">{{ healthStats.aiAdviceCount }}</div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import { useHealthStore } from '@/store/health'
import { useExerciseStore } from '@/store/exercise'
import { useDietStore } from '@/store/diet'
import { healthApi } from '@/api'
import dayjs from 'dayjs'

const userStore = useUserStore()
const healthStore = useHealthStore()
const exerciseStore = useExerciseStore()
const dietStore = useDietStore()

const profileFormRef = ref()
const passwordFormRef = ref()

const profileForm = ref({
  username: '',
  realName: '',
  gender: 1,
  birthDate: '',
  phone: '',
  email: '',
  height: null,
  targetWeight: null,
  healthGoal: '',
  healthNotes: ''
})

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const profileRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const updating = ref(false)
const passwordUpdating = ref(false)

// 健康数据统计
const healthStats = ref({
  recordDays: 0,
  exerciseCount: 0,
  dietCount: 0,
  aiAdviceCount: 0
})

// 计算属性
const age = computed(() => {
  if (!profileForm.value.birthDate) return null
  return dayjs().diff(dayjs(profileForm.value.birthDate), 'year')
})

// 方法
const disableFutureDate = (time) => {
  return time.getTime() > Date.now()
}

const loadUserInfo = async () => {
  try {
    // 如果用户已登录，总是获取最新的用户信息
    if (userStore.isLoggedIn) {
      await userStore.getUserInfo()
    }
    
    // 填充表单数据
    profileForm.value = {
      username: userStore.username || '',
      realName: userStore.realName || '',
      gender: userStore.gender || 1,
      birthDate: userStore.birthDate || '',
      phone: userStore.phone || '',
      email: userStore.email || '',
      height: userStore.height || null,
      targetWeight: userStore.targetWeight || null,
      healthGoal: userStore.healthGoal || '',
      healthNotes: userStore.healthNotes || ''
    }
  } catch (error) {
    console.error('加载用户信息失败', error)
    ElMessage.error('加载用户信息失败')
  }
}

const updateProfile = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      updating.value = true
      try {
        await userStore.updateUserInfo(profileForm.value)
        ElMessage.success('个人信息更新成功')
      } catch (error) {
        console.error('更新个人信息失败', error)
        ElMessage.error('更新失败，请重试')
      } finally {
        updating.value = false
      }
    }
  })
}

const resetForm = () => {
  loadUserInfo()
}

const updatePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordUpdating.value = true
      try {
        await userStore.changePassword({
          oldPassword: passwordForm.value.oldPassword,
          newPassword: passwordForm.value.newPassword
        })
        ElMessage.success('密码修改成功')
        resetPasswordForm()
      } catch (error) {
        console.error('修改密码失败', error)
        ElMessage.error('修改失败，请检查原密码是否正确')
      } finally {
        passwordUpdating.value = false
      }
    }
  })
}

const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
}

const loadHealthStats = async () => {
  try {
    // 获取健康记录天数
    const healthResponse = await healthStore.getRecentRecords(30)
    const healthRecords = healthResponse || []
    const uniqueDates = new Set(healthRecords.map(record => record.recordDate))
    healthStats.value.recordDays = uniqueDates.size
    
    // 获取运动记录次数
    const exerciseResponse = await exerciseStore.getRecentRecords(30)
    healthStats.value.exerciseCount = (exerciseResponse || []).length
    
    // 获取饮食记录次数
    const dietResponse = await dietStore.getRecentRecords(30)
    healthStats.value.dietCount = (dietResponse || []).length
    
    // 获取AI建议次数
    const aiResponse = await healthApi.getAdvice()
    healthStats.value.aiAdviceCount = (aiResponse || []).length
  } catch (error) {
    console.error('加载健康统计数据失败', error)
  }
}

// 生命周期
onMounted(() => {
  loadUserInfo()
  loadHealthStats()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.profile-form, .password-form {
  padding: 10px 0;
}

.stats-container {
  display: flex;
  flex-wrap: wrap;
  padding: 10px 0;
}

.stat-item {
  width: 50%;
  text-align: center;
  padding: 15px 0;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}
</style>